import 'package:binary/binary.dart';
import 'package:inmotion_protocol/base/vehicle_data.dart';
import 'package:inmotion_protocol/ezcan/bean/real_time_info.dart';
import 'package:inmotion_protocol/ezcan/protocol.dart';
import 'package:inmotion_protocol/util/byte_util.dart';
import 'package:inmotion_protocol/util/date_time_util.dart';

class EzCANHistoryStatistics extends HistoryStatistics {
  Int16 maxSpeed = Int16.zero;
  Int32 maxPower = Int32.zero;
  Int8 maxMosTemp = Int8.zero;

  Uint16 mileage = Uint16.zero;
  Uint32 energy = Uint32.zero;
  Uint32 recovery = Uint32.zero;
  Uint32 rideTime = Uint32.zero;

  @override
  int length() {
    return 0;
  }

  void calculate(AbsRealTimeInfo realTimeInfo, StatisticsMocker statisticsMocker) {
    mileage = ByteUtil.toUint16(realTimeInfo.totalMileage.value - statisticsMocker.totalMileageCountStartAt);
    rideTime = ByteUtil.toUint32(DateTimeUtil.current(second: true) - statisticsMocker.rideTimeCountStartAt);
    var tmpMaxSpeed = realTimeInfo.speed.value.abs();
    if (statisticsMocker.lastMaxSpeed < tmpMaxSpeed) {
      maxSpeed = ByteUtil.toInt16(realTimeInfo.speed.value);
      statisticsMocker.lastMaxSpeed = tmpMaxSpeed;
    } else {
      maxSpeed = ByteUtil.toInt16(statisticsMocker.lastMaxSpeed);
    }
    var tmpPower = realTimeInfo.power.value.abs();
    if (statisticsMocker.lastMaxPower < tmpPower) {
      maxPower = ByteUtil.toInt32(realTimeInfo.power.value);
      statisticsMocker.lastMaxPower = tmpPower;
    } else {
      maxPower = ByteUtil.toInt32(statisticsMocker.lastMaxPower);
    }

    var tmpMosTemp = realTimeInfo.mosTemp.value.abs();
    if (statisticsMocker.lastMaxTemp < tmpMosTemp) {
      maxMosTemp = ByteUtil.toInt8(realTimeInfo.mosTemp.value);
      statisticsMocker.lastMaxTemp = tmpMosTemp;
    } else {
      maxMosTemp = ByteUtil.toInt8(statisticsMocker.lastMaxTemp);
    }
  }

  @override
  String toString() {
    return 'EzCANHistoryStatistics{maxSpeed: $maxSpeed, maxPower: $maxPower, maxMosTemp: $maxMosTemp, mileage: $mileage, energy: $energy, recovery: $recovery, rideTime: $rideTime}';
  }
}

class EzCANTotalStatistics extends TotalStatistics {
  Uint32 mileage = Uint32.zero;
  Uint32 energy = Uint32.zero;
  Uint32 recovery = Uint32.zero;

  @override
  int length() {
    return 0;
  }

  void fromRealTimeInfo(AbsRealTimeInfo realTimeInfo) {
    mileage = Uint32(realTimeInfo.totalMileage.value);
  }

  @override
  String toString() {
    return 'EzCANTotalStatistics{mileage: $mileage, energy: $energy, recovery: $recovery}';
  }
}
